package util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import model.ExcelItem;

import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Excel 工具类
 * @author Bosen 2024/6/21 11:05
 */
public class ExcelUtils {

    public static void main(String[] args) throws Exception {
        // readExcel("d:\\Users\\PC\\Desktop\\手机号11位_1.xlsx");
        // readExcel("d:\\Users\\PC\\Desktop\\手机号11位_2.xlsx");
        // readExcel("d:\\Users\\PC\\Desktop\\手机号11位_3.xlsx");
        // writeExcel("d:\\Users\\PC\\Desktop\\Test.xlsx");
        long start = System.currentTimeMillis();
        readExcel("d:\\Users\\PC\\Desktop\\Test.xlsx");
        System.out.println("111: " + (System.currentTimeMillis() - start));
        start = System.currentTimeMillis();
        readExcel("d:\\Users\\PC\\Desktop\\Test - 副本.xlsx");
        System.out.println("111: " + (System.currentTimeMillis() - start));
    }

    public static List<ExcelItem> excelList = new LinkedList<>();

    public static void readExcel(String filepath) {
        EasyExcel.read(filepath, ExcelItem.class, new AnalysisEventListener<ExcelItem>() {
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {}
            @Override
            public void invoke(ExcelItem item, AnalysisContext analysisContext) {
                excelList.add(item);
            }
        }).sheet().doRead();
    }

    public static void writeExcel(String filepath) {
        List<ExcelItem> tempList = new LinkedList<>();
        excelList.forEach(item -> {
            Pattern pattern = Pattern.compile("^1\\d{10}$");
            Matcher matcher = pattern.matcher(item.getLevelId());
            if(!matcher.find()) {
                return;
            }
            ExcelItem temp = new ExcelItem();
            temp.setName(ChineseUtils.randomChineseName());
            temp.setAccount(item.getLevelId());
            temp.setLevelId("7515");
            temp.setAgreementId("");
            temp.setBirthday("1998/6/7");
            temp.setAddress("云南省昆明市寻甸回族彝族自治县金所乡金所村702号");
            temp.setExpireTime("-1");
            tempList.add(temp);
        });
        EasyExcel.write(filepath, ExcelItem.class).sheet().doWrite(tempList);
    }

}
